package com.yiqi.liebang.feature.home.view;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.baiiu.filter.ClassifyBo;
import com.suozhang.framework.component.http.RxDataProcessFactory;
import com.suozhang.framework.framework.AM;
import com.suozhang.framework.framework.BaseActivity;
import com.suozhang.framework.utils.T;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.yiqi.liebang.R;
import com.yiqi.liebang.common.rongim.bean.ShareQuestionBean;
import com.yiqi.liebang.common.rongim.msg.QuestionMessage;
import com.yiqi.liebang.common.widget.RatingBar;
import com.yiqi.liebang.common.widget.ShareBottomDialog;
import com.yiqi.liebang.common.widget.dialog.BaseAnimatorSet;
import com.yiqi.liebang.common.widget.dialog.BounceTopEnter;
import com.yiqi.liebang.entity.bo.SearchFriendBo;
import com.yiqi.liebang.entity.bo.UserCenterBo;
import com.yiqi.liebang.feature.home.contract.ClassifyContract;
import com.yiqi.liebang.feature.home.dependencies.classsify.ClassifyPresenterModule;
import com.yiqi.liebang.feature.home.dependencies.classsify.DaggerClassifyComponent;
import com.yiqi.liebang.feature.mine.view.AddTopicActivity;
import com.yiqi.liebang.feature.people.view.FriendsListActivity;
import com.yiqi.liebang.framework.api.HomeApi;

import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.rongcloud.contactcard.Friend;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.rong.imkit.RongIM;
import io.rong.imlib.IRongCallback;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;

public class TopicInfoActivity extends BaseActivity implements Toolbar.OnMenuItemClickListener, View.OnClickListener, ClassifyContract.View {


    @BindView(R.id.toolbar)
    Toolbar mToolbar;

    @BindView(R.id.tv_topic_type)
    TextView mTvTopicType;
    @BindView(R.id.tv_topic_title)
    TextView mTvTopicTitle;
    @BindView(R.id.tv_topic_help)
    TextView mTvTopicHelp;
    @BindView(R.id.tv_topic_date)
    TextView mTvTopicDate;
    @BindView(R.id.star)
    RatingBar mStar;
    @BindView(R.id.tv_topic_prize)
    TextView mTvTopicPrize;
    @BindView(R.id.tv_topic_prize_ago)
    TextView mTvTopicPrizeAgo;

    UMImage image;//网络图片
    UMWeb umWeb;
    ShareBottomDialog mShareDialog;
    String mTopicId;
    @BindView(R.id.tv_topic_content)
    TextView mTvTopicContent;
    @BindView(R.id.btn_topic_order)
    TextView mBtnTopicOrder;
    @BindView(R.id.view_bottom)
    LinearLayout mViewBottom;
    UserCenterBo.TopicBean mTopicData;
    @BindView(R.id.tv_topic_desc)
    TextView mTvTopicDesc;

    private boolean isEdit = false;
    private String mUserId;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_topic_info;
    }

    @Inject
    ClassifyContract.Presenter mPresenter;

    @Override
    protected void initInjector() {
        DaggerClassifyComponent.builder().classifyPresenterModule(new ClassifyPresenterModule(this)).build().inject(this);
    }


    @Override
    protected void initView() {
        mToolbar.inflateMenu(R.menu.menu_share);
        initToolBar(mToolbar, "话题详情", true, true);
        mToolbar.setOnMenuItemClickListener(this);
        mShareDialog = new ShareBottomDialog(this, null, false);
    }

    @Override
    protected void initData() {
        mTopicId = this.getIntent().getStringExtra("topic");
        mUserId = this.getIntent().getStringExtra("user_id");
        if (!TextUtils.isEmpty(mTopicId)) {
            getTopicDetail(mTopicId);
        }

    }

    @Override
    protected void onStart() {
        super.onStart();

        if (!TextUtils.isEmpty(mTopicId)) {
            getTopicDetail(mTopicId);
        }
    }

    @OnClick(R.id.btn_topic_order)
    public void onViewClicked() {
        if (isEdit) {
            Intent intent = new Intent(this, AddTopicActivity.class);
            intent.putExtra("topic", mTopicData);
            intent.putExtra("is_add", false);
            startActivityForResult(intent, 99);
        } else {
            mPresenter.getUserLabelByType(mUserId);
        }

    }

    private void getTopicDetail(String id) {
        AM.api().createApiService(HomeApi.class)
                .getTopicDetail(id)
                .compose(RxDataProcessFactory.dataPrepAndIoToMainTransformer())
                .subscribe(new Observer<UserCenterBo.TopicBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        showLoading(d);
                    }

                    @Override
                    public void onNext(UserCenterBo.TopicBean mData) {
                        if (mData != null) {
                            mTopicData = mData;
                            mTvTopicContent.setText("服务介绍：\n\n\t\t\t\t\t" + mData.getServiceIn());
                            mTvTopicDesc.setText(TextUtils.isEmpty(mData.getRemarks()) ? "" : "我想了解的学员信息：\n\n\t\t\t\t\t" + mData.getRemarks());
                            mTvTopicType.setText(mData.getServiceType() == 0 ? "线下约见" : "全国通话");
                            mTvTopicTitle.setText(mData.getTopicName());
                            mTvTopicHelp.setText("帮助过：" + mData.getUserAccountFormMap().getHelpNum() + "人");
                            mTvTopicDate.setText(mData.getServiceTime() + "小时/次");
                            mTvTopicPrize.setText(mData.getTopicPrice() + "元/次");
                            mTvTopicPrizeAgo.setText(mData.getOriginalPrice() + "元/次");
                            mTvTopicPrizeAgo.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);

                            mStar.setStar(mData.getStartLevel());
                            if (mData.getUserAccountFormMap().getUserUid().equals(AM.user().getLoginResultCache().getUserUid())) {
                                isEdit = true;
                            } else {
                                isEdit = false;
                            }
                            mBtnTopicOrder.setText(isEdit ? "修改话题" : "立即预约");
                            image = new UMImage(TopicInfoActivity.this, mData.getUserAccountFormMap().getUserHead());
                            umWeb = new UMWeb("http://liebangapp.com/yindao/");
                            umWeb.setTitle(mData.getTopicName());//标题
                            umWeb.setThumb(image);  //缩略图
                            umWeb.setDescription(mData.getRemarks());//描述

                        }
                        dismissLoading();
                    }

                    @Override
                    public void onError(Throwable e) {
                        showMsg(e.getMessage());
                        dismissLoading();
                    }

                    @Override
                    public void onComplete() {
                        dismissLoading();
                    }
                });
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        BaseAnimatorSet mBasIn = new BounceTopEnter();
        mShareDialog.showAnim(mBasIn)
                .show();
        mShareDialog.setWxCircleClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new ShareAction(TopicInfoActivity.this)
                        .setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE)//传入平台
                        .withMedia(umWeb)
                        .setCallback(shareListener)//回调监听器
                        .share();
            }
        });
        mShareDialog.setWxClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new ShareAction(TopicInfoActivity.this)
                        .setPlatform(SHARE_MEDIA.WEIXIN)//传入平台
                        .withMedia(umWeb)
                        .setCallback(shareListener)//回调监听器
                        .share();
            }
        });
        mShareDialog.setLBClickListener(this);

        return false;
    }

    private UMShareListener shareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA platform) {
            showLoading();
        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
            dismissLoading();
            T.showShort("分享成功！");
            if (mShareDialog != null) mShareDialog.dismiss();
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            dismissLoading();
            T.showShort("分享失败！");
            if (mShareDialog != null) mShareDialog.dismiss();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            dismissLoading();
            T.showShort("分享取消！");

        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 23) {
            if (data == null) return;
            Friend friend = data.getParcelableExtra("three");
            if (friend == null) return;

            ShareQuestionBean questionBean = new ShareQuestionBean(mTopicData.getTopicName(), friend.getUserUid(), "1", mTopicData.getId());
            String json = JSONObject.toJSONString(questionBean);

            QuestionMessage questionMessage = QuestionMessage.obtain(
                    "",
                    "",
                    friend.getUserUid(),
                    json,
                    mTopicData.getUserAccountFormMap().getUserUid(),
                    mTopicData.getTopicName(),
                    "2",
                    mTopicData.getId()

            );


            RongIM.getInstance().sendMessage(Message.obtain(questionBean.getShareUid(),
                    Conversation.ConversationType.PRIVATE, questionMessage), "sass", "sss",
                    new IRongCallback.ISendMessageCallback() {
                        @Override
                        public void onAttached(Message message) {

                        }

                        @Override
                        public void onSuccess(Message message) {
                            T.showShort("已发送！");
                            if (mShareDialog != null) {
                                mShareDialog.dismiss();
                            }
                            RongIM.getInstance().startConversation(TopicInfoActivity.this, Conversation.ConversationType.PRIVATE, friend.getUserUid(), friend.getUserName());
                        }

                        @Override
                        public void onError(Message message, RongIMClient.ErrorCode errorCode) {
                            T.showShort("onError" + errorCode.getMessage());
                            if (mShareDialog != null) {
                                mShareDialog.dismiss();
                            }
                        }
                    });
        } else if (requestCode == 99 && resultCode == 2) {
            finish();
        }


    }


    @Override
    public void onClick(View v) {
        Intent intent = new Intent(this, FriendsListActivity.class);
        intent.putExtra("is_select", true);
        startActivityForResult(intent, 23);
    }


    @Override
    public void showUserSuccess(String classifyBos) {
        Intent intent = new Intent(this, ReservationTopicActivity.class);
        intent.putExtra("topic", mTopicId);
        intent.putExtra("ask_lables", classifyBos);
        startActivity(intent);
        finish();
    }

    @Override
    public void showUserError(String classifyBos) {
        showMsg(classifyBos);
    }

    @Override
    public void showSuccess(List<ClassifyBo> classifyBos) {

    }

    @Override
    public void showExpert(List<SearchFriendBo.UserFriendBean> classifyBos) {

    }

    @Override
    public void showEmpty() {

    }

    @Override
    public void showError(String ex) {

    }
}
